import '../public/pwd'
import url from '../data/url'
import request from '../data/request'
import { header } from '../data/config'
import {
  numberOrCharacter as valid_numberOrCharacter,
} from '../data/validate'

const base         = url.base,
      confirmPwd   = request.confirmPwd;



// 页面标题
const title = '密码',
      action = '确认';

let form = new Vue({
  el: '#form',
  data: () => ({
    loginPassword    : '',
    loginType        : '1',
    isLock           : false
  }),
  mounted: function() {

    valid();
  }
})

function valid() {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + confirmPwd,
        type: 'POST',
        headers: header,
        data: {
          loginPassword    : form.$data.loginPassword,
          loginType        : form.$data.loginType,
        }
      })
        .done(function(res) {
          console.log(res)

          if (res.code === -1 ) {
            layer.msg(res.message || '未知错误', {
              icon: 5
            })

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './step2.html'
          }, 1000)
        })
        .fail(function(res) {
          console.log(res)

          layer.msg(`${action}${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function(res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement:function(error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      loginPassword: valid_numberOrCharacter
    }
  })
}